<template>
  <!-- 入会会费设置 -->
  <PageContainer>
    <view class="container">
      <Header title="入会会费设置" />
      <BasicsForm
        @register="formRegister"
        @submit="onSubmit"
        :show-placeholder-view="false"
        @on-schema-change="onChange"
        :label-width="120"
        :btn-group-options="{
          submit: {
            text: '确认',
          },
        }"
      ></BasicsForm>

      <ShowModal v-model="confirmVisible" title="提示" confirm-text="确认" @confirm="handleConfirm">
        <template #content>
          <div>
            <span>确认调整会员信息？</span>
            <span v-if="state == 0" class="report" @click="handleDownLoadReport">查看缴费函</span>
          </div>
        </template>
      </ShowModal>
      <ShowModal
        v-model="sendMsgVisible"
        title="会费设置成功"
        cancel-text="暂不发送"
        confirm-text="发送消息"
        :content="`是否需要发送入会缴费通知?`"
        @close="_goBack"
        @confirm="goAddMessage"
      ></ShowModal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /** 入会会费设置 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { MemberApplyById, CreatePaymenrecord, Api as adminApi } from '@/api/admin';
  import { memberServiceList, memberGroupList } from '@/api/member';
  import { navigateBack, onLoad, redirectTo } from '@/router';
  import { onMounted, ref, unref } from 'vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { type FormActionType, type FormSchema, useForm } from '@/components/Form';
  import type { IMemberApplyByIdResult, IPaymentRecordExportData } from '@/api/admin/types';
  import { memberTypeGetList } from '@/api/membership';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { Toast } from '@/utils';
  import { ShareTypeEnum } from '@/enums/shareEnum';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { onShareAppMessage } from '@dcloudio/uni-app';
  import ShowModal from '@/components/ShowModal/index.vue';
  import type { OnchangeArgument } from '@/components/Form/types';
  import type { MemberTypeGetListItem } from '@/api/membership/types';
  import dayjs from 'dayjs';
  import { useEnv } from '@/hooks/core/useEnv';
  import { useUpload } from '@/hooks/core/useUpload';
  import { PaymentStatusEnum } from '@/enums/membershipEnum';
  import { UniEmitNameEnum } from '@/enums/uniEmitEnum';
  import { useAppShare } from '@/hooks/core/useAppShare';

  const { setWxSharePath } = useAppShare();

  let refresh: (() => void) | undefined;
  interface IDefaultData {
    id: number;
    memberName?: string;
    levelName?: string;
    levelId?: number;
    applyType?: number;
  }

  const defaultData = ref<IDefaultData>({
    id: 0,
    memberName: '',
    levelName: '',
    levelId: 0,
    applyType: 1,
  });

  const reqData = ref<IMemberApplyByIdResult>();
  const confirmVisible = ref(false);
  const sendMsgVisible = ref(false);
  const { globalConfig } = useAppStoreWithOut();

  const selectOptions = ref<{ [x: string]: MemberTypeGetListItem[] }>();
  const reportData = ref<IPaymentRecordExportData>({
    memberName: '',
    levelName: '',
    amountPaid: 0,
    membershipFees: 0,
    applyType: 1,
    unit: 12,
  });
  const state = ref<number>();

  const [register, { setFieldsValue, getFieldsValue, updateSchema, appendSchemaByField }] = useForm(
    {
      labelAlign: 'left',
      validateTrigger: 'bind',
      schemas: [],
    },
  );

  function formRegister(instance: FormActionType) {
    register(instance);
    getSettingInfo();
  }

  const formStateDisabled = ref(false);

  const getSettingInfo = async () => {
    try {
      reqData.value = await MemberApplyById(defaultData.value.id);

      console.log('res--->', reqData.value);
      const fields: FormSchema[] = [
        {
          field: 'memberName',
          label: '会员名称',
          component: 'Input',
          dynamicDisabled: true,
          defaultValue: defaultData.value?.memberName,
        },
        {
          field: 'levelName',
          label: '申请职务',
          component: 'Input',
          dynamicDisabled: true,
          defaultValue: defaultData.value.levelName,
        },
        {
          field: 'state',
          label: '缴费状态',
          component: 'RadioGroup',
          required: true,
          isOnChange: true,
          defaultValue: reqData.value?.state || PaymentStatusEnum.NOTPAYCOST,
          dynamicDisabled: () => formStateDisabled.value,
          componentProps: {
            localdata: [
              { text: '待缴费', value: 0 },
              { text: '已缴费', value: 1 },
            ],
          },
        },
        {
          field: 'levelId',
          label: '实际职务',
          component: 'Select',
          defaultValue: reqData.value?.nowLevelId || defaultData.value.levelId,
          componentProps: {
            localdata: [],
          },
        },
        {
          field: 'standard',
          label: '会费标准',
          component: 'Input',
          dynamicDisabled: true,
        },
        {
          field: 'payMoney',
          label: '应缴金额（￥）',
          component: 'Input',
          dynamicDisabled: () => formStateDisabled.value,
        },
        {
          field: 'startTime',
          label: '会籍开始时间',
          component: 'DatePicker',
          required: true,
          isOnChange: true,
          defaultValue: reqData.value?.startTime || dayjs().format('YYYY-MM-DD'),
        },
        {
          field: 'endTime',
          label: '会籍结束时间',
          component: 'DatePicker',
          required: true,
          // defaultValue: reqData.value?.endTime,
        },
        {
          field: 'paymentVoucher',
          label: '缴费凭证',
          ifShow: reqData.value?.state == 1,
          component: 'UploadImg',
          defaultValue: reqData.value?.paymentVoucher,
          componentProps: {
            limit: 1,
          },
        },
        {
          field: 'show',
          label: '负责人、企业对外展示',
          component: 'Switch',
          defaultValue: reqData.value ? reqData.value?.memberOtherSettingsDto?.show === 1 : true,
        },
        {
          field: 'currentService',
          label: '服务专员',
          component: 'Select',
          defaultValue: reqData.value?.memberOtherSettingsDto?.currentService,
          componentProps: {
            localdata: [],
          },
        },
        {
          field: 'remarks',
          label: '备注',
          component: 'InputTextArea',
          defaultValue: reqData.value?.memberOtherSettingsDto?.remarks,
          componentProps: {
            placeholder: '该备注会员可见',
          },
        },
        {
          field: 'groupIdList',
          label: '标签分组',
          component: 'CheckboxGroup',
          defaultValue: reqData.value?.memberOtherSettingsDto?.groupIdList,
          itemProps: {
            labelPosition: 'top',
          },
          componentProps: {
            localdata: [],
          },
        },
      ];

      for (let i = 0; i < fields.length; i++) {
        const item = fields[i];
        appendSchemaByField({
          ...item,
        } as FormSchema);
      }

      const typeDataName = [
        { field: 'levelId', type: 'memberLevel' },
        { field: 'memberPostId', type: 'memberPost' },
      ];
      selectOptions.value = await memberTypeGetList(typeDataName.map((v) => v.type));
      for (let index = 0; index < typeDataName.length; index++) {
        const item = typeDataName[index];
        updateSchema({
          field: item.field,
          isOnChange: true,
          componentProps: {
            localdata: localDataMapping(selectOptions.value[item.type], {
              label: 'name',
              value: 'id',
            }),
          },
        });
      }

      let levelItem = selectOptions.value['memberLevel'].find(
        (f) => f.id === defaultData.value.levelId,
      );

      const _allottedTime = unref(reqData)?.allottedTime ?? levelItem?.allottedTime ?? 0;
      const _startTime = unref(reqData)?.startTime ?? dayjs().format('YYYY-MM-DD');
      const money = reqData.value?.payMoney ?? levelItem?.membershipFees ?? 0;

      updateSchema([
        {
          field: 'standard',
          defaultValue: `${money}元/${_allottedTime}月`,
        },
        {
          field: 'payMoney',
          defaultValue: money,
        },
        {
          field: 'endTime',
          defaultValue:
            reqData.value?.endTime ||
            dayjs(_startTime)
              .add(_allottedTime as number, 'month')
              .format('YYYY-MM-DD'),
        },
      ]);

      if (Number(money) <= 0) {
        formStateDisabled.value = true;
        setFieldsValue({ state: PaymentStatusEnum.ALREADYPAYCOST });
      }

      let serviceRes = await memberServiceList();
      updateSchema({
        field: 'currentService',
        componentProps: {
          localdata: localDataMapping(serviceRes, { label: 'userName', value: 'id' }),
        },
      });

      let groupRes = await memberGroupList();
      updateSchema({
        field: 'groupIdList',
        componentProps: {
          localdata: localDataMapping(groupRes, { label: 'name', value: 'id' }),
        },
      });

      reportData.value.memberName = defaultData.value?.memberName;
      reportData.value.levelName = reqData.value?.nowLevelName || levelItem?.name;
      reportData.value.membershipFees = reqData.value?.money ?? levelItem?.membershipFees ?? 0;
      reportData.value.applyType = defaultData.value?.applyType;
      reportData.value.unit = _allottedTime;
    } catch (error) {
      console.error(error);
    }
  };

  function onChange(e: OnchangeArgument) {
    console.log(e);
    if (e.field === 'levelId') {
      let item =
        selectOptions.value && selectOptions.value['memberLevel'].find((f: any) => f.id === e.val);
      setFieldsValue({ standard: `${item?.membershipFees}元/${item?.allottedTime}月` });
      setFieldsValue({ payMoney: item?.membershipFees });
      const { startTime } = getFieldsValue();
      setFieldsValue({
        endTime: dayjs(startTime)
          .add(item?.allottedTime as number, 'month')
          .format('YYYY-MM-DD'),
      });
      const state = item?.membershipFees ? 0 : 1;
      formStateDisabled.value = item?.membershipFees ? false : true;

      setFieldsValue({
        state: state,
      });

      updateSchema([
        {
          field: 'paymentVoucher',
          ifShow: state == PaymentStatusEnum.ALREADYPAYCOST,
        },
      ]);
      reportData.value.levelName = item?.name;
      reportData.value.unit = item?.allottedTime;
      reportData.value.membershipFees = item?.membershipFees;
    } else if (e.field === 'startTime') {
      setFieldsValue({
        endTime: dayjs(e.val)
          .add(unref(reportData).unit as number, 'month')
          .format('YYYY-MM-DD'),
      });
    } else if (e.field === 'state') {
      updateSchema({
        field: 'paymentVoucher',
        ifShow: e.val == PaymentStatusEnum.ALREADYPAYCOST,
      });
    }
  }

  const onSubmit = (e: any) => {
    let { payMoney, state: state2, startTime, endTime } = getFieldsValue();
    state.value = state2;
    if (dayjs(startTime).unix() >= dayjs(endTime).unix()) {
      Toast('结束时间需大于开始时间');
      return;
    }
    if (payMoney == 0 && state2 == 0) return Toast('金额为0无需支付，请设为已缴费');
    confirmVisible.value = true;
  };

  // 下载缴费函
  const { getEnv } = useEnv();
  const { openDocument } = useUpload();
  function handleDownLoadReport() {
    let { payMoney, startTime, endTime } = getFieldsValue();
    startTime = dayjs(startTime).format('YYYY-MM-DD');
    endTime = dayjs(endTime).format('YYYY-MM-DD');
    openDocument({
      filePath:
        getEnv('BASE_URL') +
        adminApi.paymentRecordExport +
        `?memberName=${defaultData.value.memberName}&levelName=${defaultData.value.levelName}
        &nowLevelName=${reportData.value.levelName}&membershipFees=${
          reportData.value.membershipFees
        }&amountPaid=${payMoney}
        &applyType=${reportData.value.applyType}&startTime=${startTime}&endTime=${endTime}&unit=${
          (reportData.value.unit as number) / 12 + '年'
        }&allottedTime=${reportData.value.unit}`,
      fileType: 'pdf',
      customFileName: `${defaultData.value.memberName}-入会缴费函`,
    });
  }

  const sendUserId = ref<String>();
  function handleConfirm() {
    const {
      levelId,
      startTime,
      endTime,
      payMoney,
      state,
      show,
      memberPostId,
      groupIdList,
      currentService,
      remarks,
      paymentVoucher,
    } = getFieldsValue();
    CreatePaymenrecord({
      applyId: defaultData.value.id,
      levelId,
      paymentVoucher,
      startTime,
      endTime,
      payMoney,
      state,
      memberOtherSettingsDto: {
        show: show ? 1 : 0,
        memberPostId,
        groupIdList,
        currentService,
        remarks,
      },
    }).then((res) => {
      refresh?.();
      if (state == 1) {
        // 设为已缴费
        _goBack();
      } else {
        sendMsgVisible.value = true;
        sendUserId.value = res.userId; // 发送消息必须取后端返回拼接的ID,否则可能ID不一致
      }
    });
  }
  // 跳转发送消息页面
  const goAddMessage = () => {
    redirectTo({
      name: 'addMessage',
      options: {
        userIds: [unref(sendUserId)],
        typeId: 16, // 写死入会缴费通知类型
      },
    });
  };

  const _goBack = () => {
    uni.$emit(UniEmitNameEnum.REFRESHPREVIOUSPAGE);
    navigateBack();
  };

  onLoad<'DuesSet'>((op) => {
    refresh = op.refresh;
    defaultData.value.id = op.id;
    defaultData.value.levelId = op.levelId;
    defaultData.value.levelName = op.levelName;
    defaultData.value.memberName = op.memberName;
    defaultData.value.applyType = op.applyType;
  });

  const { hasShareImgConfig } = useAppStoreWithOut();

  onShareAppMessage(() => {
    const membershipShare = hasShareImgConfig(ShareTypeEnum.membership);
    return {
      path: setWxSharePath({ name: 'updateMembershipInfo' }),
      imageUrl: membershipShare?.iconUrl,
      title: membershipShare?.desc,
    };
  });
</script>

<style lang="scss" scoped>
  $color-primary: #2878ff;
  .container {
    padding-top: 30rpx;
    background-color: #fff;
    .report {
      color: $color-primary;
    }
  }
</style>
